#!/usr/bin/env bash

GCC_VERSION=13.3.0
if [[ $# -eq 1 ]] ; then
  GCC_VERSION=$1
fi
GIT_REPO=git://gcc.gnu.org/git/gcc.git
SRCDIR=${HOME}/software
REPO=${SRCDIR}/gcc
BUILD=${REPO}/build
PREFIX=${HOME}/gcc-${GCC_VERSION}
export LC_ALL=C

OS=$(uname -s)
case ${OS} in
  Linux)
    MAKE=make
    MAKEFLAGS="-j$(($(grep -c '^processor' /proc/cpuinfo) + 1))"
    ;;
  FreeBSD)
    MAKE=gmake
    MAKEFLAGS="-j$(sysctl -n hw.ncpu)"
    ;;
  *)
    echo "Unsupported OS"
    exit 1
    ;;
esac
export MAKEFLAGS

rm -rf   ${BUILD}     || exit $?
rm -rf   ${PREFIX}    || exit $?
mkdir -p ${SRCDIR}    || exit $?

if [ ! -e ${REPO} ]; then
  cd ${SRCDIR}
  git clone ${GIT_REPO} gcc || exit $?
fi

cd       ${REPO}                         || exit $?
git checkout releases/gcc-${GCC_VERSION} || exit $?
rm -rf gmp* mpfr* mpc* isl*              || exit $?
./contrib/download_prerequisites
mkdir -p ${BUILD}                        || exit $?
cd       ${BUILD}                        || exit $?

${REPO}/configure            \
  --disable-linux-futex     \
  --disable-mudflap         \
  --disable-nls             \
  --enable-languages=c,c++  \
  --enable-threads=posix    \
  --enable-tls              \
  --prefix=$PREFIX

time { ${MAKE} -s && ${MAKE} -s install; }
